import React, { useState } from 'react';
import { 
  Box, 
  Typography,
  useMediaQuery,
  useTheme,
  Menu,
  MenuItem,
  ListItemIcon
} from '@mui/material';
import { useLocation, useNavigate } from 'react-router-dom';
import PersonIcon from '@mui/icons-material/Person';
import MenuIcon from '@mui/icons-material/Menu';
import GitHubIcon from '@mui/icons-material/GitHub';
import LoginIcon from '@mui/icons-material/Login';
import LogoutIcon from '@mui/icons-material/Logout';
import { useAuth } from 'contexts/AuthContext';
import { useDarkMode } from 'contexts/DarkMode';
import PortalHamburgerButton from 'components/atoms/PortalHamburgerButton';
import LogoComponent from 'components/atoms/LogoComponent';
import backgroundImage from 'images/backgroundImage.gif';
import backgroundLoader from 'images/backgroundLoader.gif';

// Import the styled components from our separate file
import {
  DarkModeSwitch,
  StyledAppBar,
  StyledToolbar,
  StyledButton
} from './styledComponents';

const TopIcons = ({ 
  isHomePage: propsIsHomePage, 
  toggleDashboardDrawer,
  toggleDashboardDrawerProtected, 
  toggleMenu, 
  useCover = true,
  boxHeight = '100vh',
  darkMode: propsDarkMode,
  useOverlay = true,
  useLoader = false,
  useOptions = false
}) => {
  const location = useLocation();
  const navigate = useNavigate();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.only('xs'));
  const { darkMode: contextDarkMode, setDarkMode } = useDarkMode();
  const { user } = useAuth();
  
  // State for menu anchor
  const [menuAnchorEl, setMenuAnchorEl] = useState(null);
  const isMenuOpen = Boolean(menuAnchorEl);
  
  const isHomePage = location.pathname === '/home-page';
  
  const handleMenuOpen = (event) => {
    setMenuAnchorEl(event.currentTarget);
  };
  
  const handleMenuClose = () => {
    setMenuAnchorEl(null);
  };
  
  const navigatePage = (url) => {
    window.open(url, '_blank', 'noopener,noreferrer');
    handleMenuClose();
  };

  const navigateOpen = (path) => {
    if (path === 'toggleDashboardDrawer') {
      if (isMobile) {
        if (toggleDashboardDrawer) {
          toggleDashboardDrawer();
        }
      } else {
        if (toggleDashboardDrawerProtected) {
          toggleDashboardDrawerProtected();
        }
      }
    } else {
      navigate(path);
      if (isMobile) {
        if (toggleDashboardDrawer) {
          toggleDashboardDrawer(false);
        }
      } else {
        if (toggleDashboardDrawerProtected) {
          toggleDashboardDrawerProtected(false);
        }
      }
    }
    handleMenuClose();
  };
 
  const appBarContent = (
    <Box
      sx={{
        position: isHomePage ? 'fixed' : 'sticky',
        top: 0,
        left: 0,
        right: 0,
        zIndex: (theme) => theme.zIndex.drawer - 1,
        backgroundColor: contextDarkMode ? 'black' : 'white',
      }}
    >
      <StyledAppBar 
        position="static"
        elevation={0}
        darkMode={contextDarkMode}
      >
        <StyledToolbar 
          disableGutters
          darkMode={contextDarkMode}
          sx={{
            maxWidth: {
              xs: '100%',
              sm: '600px',
              md: '960px',
              lg: '1280px',
              xl: '1920px'
            },
            mx: 'auto',
          }}
        >
          <LogoComponent 
            darkMode={contextDarkMode} 
            isHomePage={isHomePage}
            logoText="startersaaskit.com"
            showPlayIcon={true}
            toggleDashboardDrawer={isMobile ? toggleDashboardDrawer : toggleDashboardDrawerProtected}
            fontSize="1.5rem"
          />
          
          <Box sx={{ display: 'flex', alignItems: 'center' }}>
            <PortalHamburgerButton 
              onToggle={() => isMobile ? toggleDashboardDrawer(true) : toggleDashboardDrawerProtected(true)} 
              id="my-hamburger" 
              className="my-custom-class"
              style={{ marginTop: 5 }}
              darkMode={contextDarkMode}
            />
          </Box>
        </StyledToolbar>
      </StyledAppBar>
      
      {useOptions && (
        <StyledAppBar 
          position="static"
          elevation={0}
          darkMode={contextDarkMode}
          sx={{ marginTop: 0 }}
        >
          <StyledToolbar 
            disableGutters
            darkMode={contextDarkMode}
            sx={{
              maxWidth: {
                xs: '100%',
                sm: '600px',
                md: '960px',
                lg: '1280px',
                xl: '1920px'
              },
              mx: 'auto',
            }}
          >
            {/* Dark Mode Toggle on the left */}
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <DarkModeSwitch 
                checked={contextDarkMode}
                onChange={() => setDarkMode(!contextDarkMode)}
                inputProps={{ 'aria-label': 'toggle dark mode' }}
              />
            </Box>
            
            {/* Buttons on the right */}
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <StyledButton
                onClick={() => navigateOpen('/dashboard')}
                startIcon={<PersonIcon />}
                darkMode={contextDarkMode}
                sx={{ marginRight: 1 }}
              >
                Dashboard
              </StyledButton>
              
              <StyledButton
                onClick={handleMenuOpen}
                startIcon={<MenuIcon />}
                darkMode={contextDarkMode}
                aria-controls={isMenuOpen ? 'menu-dropdown' : undefined}
                aria-haspopup="true"
                aria-expanded={isMenuOpen ? 'true' : undefined}
              >
                Menu
              </StyledButton>
              
              {/* Dropdown Menu */}
              <Menu
                id="menu-dropdown"
                anchorEl={menuAnchorEl}
                open={isMenuOpen}
                onClose={handleMenuClose}
                MenuListProps={{
                  'aria-labelledby': 'menu-button',
                }}
                PaperProps={{
                  elevation: 3,
                  sx: {
                    mt: 1.5,
                    borderRadius: '10px',
                    backgroundColor: contextDarkMode ? theme.palette.grey[900] : 'white',
                  }
                }}
                transformOrigin={{ horizontal: 'right', vertical: 'top' }}
                anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
              >
                {/* GitHub Links */}
                <MenuItem onClick={() => navigatePage('https://github.com/startersaas/startersaas-backend-go-api-main.git')}>
                  <ListItemIcon>
                    <GitHubIcon fontSize="small" />
                  </ListItemIcon>
                  Go API
                </MenuItem>
                <MenuItem onClick={() => navigatePage('https://github.com/startersaas/startersaas-backend-node-api-main.git')}>
                  <ListItemIcon>
                    <GitHubIcon fontSize="small" />
                  </ListItemIcon>
                  Node API
                </MenuItem>
                <MenuItem onClick={() => navigatePage('https://github.com/startersaas/startersaas-frontend-react-spa.git')}>
                  <ListItemIcon>
                    <GitHubIcon fontSize="small" />
                  </ListItemIcon>
                  React API
                </MenuItem>
                
                {/* Login/Logout based on user authentication */}
                {user ? (
                  <MenuItem onClick={() => navigateOpen('/auth/logout')}>
                    <ListItemIcon>
                      <LogoutIcon fontSize="small" />
                    </ListItemIcon>
                    Logout
                  </MenuItem>
                ) : (
                  <MenuItem onClick={() => navigateOpen('/auth/login')}>
                    <ListItemIcon>
                      <LoginIcon fontSize="small" />
                    </ListItemIcon>
                    Login
                  </MenuItem>
                )}
              </Menu>
            </Box>
          </StyledToolbar>
        </StyledAppBar>
      )}
    </Box>
  );
  
  if (isHomePage) {
    return (
      <>
        <Box
          sx={{
            height: boxHeight,
            width: '100%',
            position: 'relative',
            overflow: 'hidden',
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'flex-end',
            backgroundImage: `url(${contextDarkMode && useLoader ? backgroundLoader : backgroundImage})`,
            backgroundPosition: 'center bottom',
            backgroundRepeat: 'no-repeat',
            backgroundSize: useCover ? 'cover' : 'auto',
            ...(contextDarkMode && useOverlay && {
              '&::before': {
                content: '""',
                position: 'absolute',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                backgroundColor: theme.palette.background.default,
                opacity: 0.95,
                zIndex: 0,
              }
            })
          }}
        >
          {/* New Call-to-Action Buttons */}
          <Box 
            sx={{ 
              position: 'absolute',
              top: '25%',
              left: '50%',
              transform: 'translateX(-50%)',
              display: 'flex',
              gap: '16px',
              zIndex: 1,
            }}
          >
            <StyledButton
              onClick={() => navigateOpen('/auth/login')}
              darkMode={contextDarkMode}
              variant="contained"
              sx={{ 
                padding: '10px 30px',
                fontSize: '1.1rem',
                fontWeight: 'bold'
              }}
            >
              Demo
            </StyledButton>
            
            <StyledButton
              onClick={() => navigateOpen('/auth/register')}
              darkMode={contextDarkMode}
              variant="contained"
              sx={{ 
                padding: '10px 30px',
                fontSize: '1.1rem',
                fontWeight: 'bold'
              }}
            >
              Signup
            </StyledButton>
          </Box>
          
          <Box 
            sx={{ 
              marginBottom: '4rem',
              textAlign: 'center',
              padding: '0 1rem',
              zIndex: 1,
            }}
          >
            <Typography 
              variant="h3" 
              component="h1" 
              sx={{ 
                fontWeight: 'bold',
                fontFamily: 'Poppins',
                color: 'white',
                marginBottom: '1rem'
              }}
            >
              Premium FSBO Leads for Agents
            </Typography>
            <Typography 
              variant="h4" 
              component="h2" 
              sx={{ 
                fontWeight: 'bold',
                fontFamily: 'Poppins', 
                color: 'white'
              }}
            >
              Launch Your Property Listing Referral Today
            </Typography>
          </Box>
        </Box>
        
        {appBarContent}
      </>
    );
  }
  
  return (
    <>
      {appBarContent}
    </>
  );
};

export default TopIcons;